﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using CommonSense.UI.Shell.ViewModels;
using CommonSense.UI.Shell.Interfaces;

namespace CommonSense.UI.Shell.Services
{
    class ViewModelFactory : IViewModelFactory
    {
        private IModuleService moduleService;

        public ViewModelFactory(IModuleService moduleService)
        {
            this.moduleService = moduleService;
            this.moduleService.DIContainer.RegisterSingletonInstance<IViewModelFactory>(this);
        }

        public TViewModel Create<TViewModel>() where TViewModel : BaseViewModel
        {
            Type viewModelType = typeof(TViewModel);
            TViewModel viewModelInstance = (TViewModel)this.moduleService.CreateInstance(viewModelType);

            Type viewType = this.moduleService.GetViewForViewModel(viewModelType);
            FrameworkElement view = (FrameworkElement)this.moduleService.CreateInstance(viewType);

            viewModelInstance.View = view;
            view.DataContext = viewModelInstance;

            return viewModelInstance;
        }
    }
}
